package com.java.threaddemo2;

public class WarehouseStack {
	/**
	 * 仓库的建立
	 */
	// 属性
	// (1)栈元素,whStack是数组的名字
	private Product[] whStack;
	// (2)栈顶指针
	private int size = 0;
	// (3)栈的容量
	private int capacity;

	// 行为
	// (1)构造方法
	public WarehouseStack() {
		init();
	}

	public WarehouseStack(int capacity) {
		this.capacity = capacity;
		init();
	}

	// (2)初始化
	public void init() {
		if (capacity == 0) {
			capacity = 10;
		}
		whStack = new Product[capacity];// 创建一个新数组

	}

	// (3)入栈:只有生产者生产的产品才入栈
	public void push(Product obj) {
		// 同步语句块
		synchronized (this) {
			// 判断栈顶指针是否等于栈的容量
			if (size == capacity) {
				System.out.println("仓库已满，生产者进入等待阶段！");
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			whStack[size] = obj;
			size++;
			this.notifyAll();
		}

	}

	// (4)出栈：只有消费者消费的产品才出栈
	public Product pop() {
		// 同步语句块
		synchronized (this) {
			// 判断栈顶指针是否为0
			if (size == 0) {
				System.out.println("仓库已空，消费者进入等待阶段！");
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			size--;
			Product obj = whStack[size];
			this.notifyAll();

			return obj;
		}

	}
	// (5)getter，setter

	public Product[] getWhStack() {
		return whStack;
	}

	public void setWhStack(Product[] whStack) {
		this.whStack = whStack;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public int getCapacity() {
		return capacity;
	}

	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}

}
